package com.kehao.newcoder;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class NC137Solution {
    public int solve(String s) {
        List initList = init(s);
        return cal(initList,0)[0];
    }

    private int[] cal(List initList, int start) {
        Stack<Integer> numStack = new Stack<>();
        char op = '+';
        int i = start;
        for (; i < initList.size(); i++) {
            Object o = initList.get(i);
            if(o.equals(')')){
                break;
            }else if(o.equals('+')||o.equals('-')||o.equals('*')){
                op = (Character) o;
                continue;
            }
            int num = 0;

            if(o instanceof Integer){
                num = (Integer) o;
            }
            else if(o.equals('(')){
                int[] ans = cal(initList, i + 1);
                i = ans[1];
                num = ans[0];
            }
            switch (op){
                case '+':
                    numStack.push(num);
                    break;
                case '-':
                    numStack.push(-num);
                    break;
                case '*':
                    numStack.push(numStack.pop()*num);
                    break;
            }
        }
        int sum = 0;
        while(!numStack.isEmpty()){
            sum +=numStack.pop();
        }
        return new int[]{sum,i};
    }

    private List init(String s) {
        List list = new ArrayList<>();
        char[] charArray = s.toCharArray();

        int i =0;
        while (i<charArray.length){
            int num = 0;
            boolean showNum = false;
            while (i<charArray.length&&charArray[i] >= '0' && charArray[i] <= '9') {
                num = num * 10 + charArray[i] - '0';
                showNum = true;
                i++;
            }
            if(showNum){
                list.add(num);
            }
            if(i<charArray.length){
                list.add(charArray[i]);
                i++;
            }
        }
        return list;
    }

    @Test
    public void test01() {
        System.out.println(solve("(2*(3-4))*5"));
    }


}
